from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from utils.tencent.sms import send_sms_single
from django.conf import settings
from web import models
from web.forms.project import ProjectModelForm 

from django.db.models import Count, Avg, Max, Min, Sum

from web.views import dashboard
import datetime
import time
import collections
def dashboard(request,project_id):
    
    # 项目状态    
    status_dict = {}
    # status_dict = collections.OrderedDict()
    for value, text in models.Issues.status_choices:
        status_dict[value] = {'text':text,'count':0}

    items = models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
    
    for item in items:
        status_dict[item['status']]['count'] = item['ct']
    
    
    #项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values_list('user_id','user__username')
    
    top_ten_assigned_issues = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by('-id')[0:100]
    
    
    
    context = {
       'status_dict':status_dict,
       'user_list':user_list,
       'top_ten_assigned_issues':top_ten_assigned_issues,
    }
    return render(request,"web/dashboard.html",context)

def issue_chart(request,project_id):
    ret = {'status':True, 'data':''}
    # data = [[85877845971，9],[85877845971，9],]
    today = datetime.datetime.now().date()
    result = models.Issues.objects.filter(project_id=project_id,
                                        create_datetime__gte=today-datetime.timedelta(days=30)).extra(
                                            select={'ctime':"strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}
                                        ).values('ctime').annotate(ct=Count('id'))
    date_dict = collections.OrderedDict()
    for i in range(0,30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] =[time.mktime(date.timetuple())*1000, 0]
    
    for item in result:
        date_dict[item['ctime']][1] = item['ct']
   
    ret['data'] = list(date_dict.values()) 
    
    return JsonResponse(ret)